<template>
  <el-dialog
    v-model="show"
    :title="isUpdate ? '修改商品类型' : '新增商品类型'"
    width="600px"
    @close="closeModal"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="商品名称" required prop="SeriesName">
        <el-input
          v-model="form.SeriesName"
          placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="SeriesAvatar">
        <ImageUpload
          v-model="form.SeriesAvatar"
          @getImgName="(n) => (form.SeriesImgName = n)"
        ></ImageUpload>
      </el-form-item>
      <el-form-item label="商品类目">
        <el-input
          v-model="form.ProductTypeName"
          placeholder="请输入商品类目"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品品牌" prop="BrandName">
        <el-input v-model="form.BrandName" placeholder="请输入商品品牌" />
      </el-form-item>
      <el-form-item label="参考价" prop="RecommandPrice">
        <el-input
          v-model.number="form.RecommandPrice"
          type="number"
          placeholder="请输入参考价"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品推荐" prop="RecommandLevel">
        <el-input
          v-model="form.RecommandLevel"
          placeholder="商品推荐程度"
        ></el-input>
      </el-form-item>
      <el-form-item label="销量" prop="SalesVolume">
        <el-input v-model="form.SalesVolume" placeholder="商品销量"></el-input>
      </el-form-item>
      <el-form-item label="订单属性设置">
        <el-button type="primary" plain link @click="turnPageTo">
          <span class="mr-1">设置</span>
          <Edit size="4" class="text-blue-400" />
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="handleConfirm(formRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { computed, reactive, toRef, toRefs, watch } from "vue";
import { errMsg } from "@/utils/errorMsg";
import { Edit } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import useOrderAttrStore from "@/store/modules/orderAttrs";
import { seriesQueryApi } from "@/api/order/series";
const router = useRouter();

defineOptions({
  name: "CalcEditModal",
});
const orderStore = useOrderAttrStore();
const props = defineProps({
  open: {
    type: Boolean,
    required: true,
  },
  isUpdate: {
    type: Boolean,
    required: true,
  },
  data: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(["closeModal", "reload"]);

const state = reactive({
  form: {
    SeriesName: "",
    SeriesAvatar: "",
    ProductTypeName: ``,
    BrandName: "",
    RecommandPrice: "",
    SeriesImgName: "",
    RecommandLevel: "",
    SalesVolume: "",
    attrs: [],
  },
  formRef: undefined,
  rules: {
    SeriesName: [
      { required: true, message: "请输入类型名称", triggger: "change" },
      {
        triggger: "change",
        validator: checkRepeat,
      },
    ],
  },
  seriesList: [],
});

const { form, formRef, rules, seriesList } = toRefs(state);
watch(
  () => props.open,
  async (val) => {
    show.value = val;
    form.value = {
      SeriesId: 0,
      SeriesName: "",
      SeriesAvatar: "",
      ProductTypeName: ``,
      BrandName: "",
      RecommandPrice: "",
      SeriesImgName: "",
      RecommandLevel: "",
      SalesVolume: "",
      attrs: [],
    };
    form.value = Object.assign(form.value, props.data);
    if (!props.isUpdate) {
      for (let key in form.value) {
        if (Array.isArray(form.value[key])) form.value[key] = [];
        else form.value[key] = "";
      }
    }
    const res = await seriesQueryApi();
    seriesList.value = res.Data || [];
  }
);
const show = ref(false);

function closeModal() {
  show.value = false;
  emits("closeModal");
}

function handleConfirm(submitFormRef) {
  submitFormRef.validate((valid, fields) => {
    if (valid) {
      try {
        // 接口请求
        if (props.isUpdate) {
          emits("reload", form.value, true);
        } else {
          emits("reload", form.value, false);
        }
        // emits('reload', form.value)
      } catch (error) {
        console.error("未知错误", error);
        // 请求失败处理
        ElMessage.error("修改失败：" + errMsg(error));
      }
      closeModal();
    }
  });
}
function turnPageTo() {
  if (seriesList.value.some((item) => item.SeriesId == form.value.SeriesId)) {
    orderStore.setCurrentSeries(form.value);
    router.push({ path: "./attrs" });
  } else {
    ElMessage({
      type: "warning",
      message: "未找到商品名称，请先创建商品",
    });
  }
}
function checkRepeat(rule, value, callback) {
  let names = orderStore.orderAttrs.map((item) => item.name);
  if (names.includes(value) && value != form.value.SeriesName) {
    callback("已存在相同商品名称");
  }
  callback();
}
</script>
<style lang="scss">
</style>